package at.irian.jsfatwork.web.model;

import at.irian.jsfatwork.domain.Project;
import at.irian.jsfatwork.domain.Resource;
import at.irian.jsfatwork.domain.Task;
import at.irian.jsfatwork.domain.TaskStatus;
import org.apache.myfaces.orchestra.viewController.annotations.InitView;
import org.apache.myfaces.orchestra.viewController.annotations.PreRenderView;
import org.apache.myfaces.orchestra.viewController.annotations.ViewController;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import java.util.Arrays;
import java.util.List;

/**
 * @author Thomas Spiegl, IRIAN Solutions GmbH
 */
@Repository
@Scope("conversation.flash")
@ViewController(viewIds = {"/task1.xhtml","/task2.xhtml","/task3.xhtml"})
public class TaskBean extends DetailListBean<Task> {

    public TaskBean() {
        super(Task.class, 10);
    }

    @InitView
    @PreRenderView
    public void beforeRender() {
        if (getEntity() == null) {
            String viewId = FacesContext.getCurrentInstance().getViewRoot().getViewId();
            if (viewId.equals("/task1.xhtml") || viewId.equals("/task2.xhtml") || viewId.equals("/task3.xhtml")) {
                FacesContext.getCurrentInstance().getApplication().getNavigationHandler().handleNavigation(
                        FacesContext.getCurrentInstance(), null, "/tasks.xhtml");
            }
        }
    }

    public Converter getProjectConverter() {
        return new EntityConverter(Project.class, "taskBean");
    }

    public Converter getResourceConverter() {
        return new EntityConverter(Resource.class, "taskBean");
    }

    public List<TaskStatus> getTaskStatusSelectItems() {
        return Arrays.asList(TaskStatus.values());
    }

    public String addNewMultipleSteps() {
        addNew();
        return "/task1.xhtml";
    }

    public String cancelBackToTasks() {
        cancel();
        return "/tasks.xhtml";
    }

}